<template>
  <div>
    <button-change-cart
      v-if="addCartButtonType !=0"
      :type="addCartButtonType"
      :number="showNum"
      :goodsType="goodsType"
      :stockCount="isStockCount"
      :weightType="weightType"
      :isStockCountOver="isStockCountOver"
      @subFromCart="subFromCart"
      @addToCart="addToCart">
    </button-change-cart>
    <slot name="button"
          :stockCount="isStockCount"
          :number="showNum"
          :goodsType="goodsType"
          :goodsUnit=" goodsType== 6 || goodsType == 7 ? 'g' :'' "
          :add="addToCart"
          :sub="subFromCart">
    </slot>
  </div>
</template>
<script>


  import ButtonChangeCart from '../ButtonChangeCart'
  import DetailProce from '../DetailProce'
  import {mapGetters, mapActions} from 'vuex'
  import {MessageBox} from '@/ui-components'
  import {Toast} from '@/utils/toast'
  import getConfig from '../../utils/CJY/getConfig'

  export default {
    data() {
      return {
        number: 0,
        rid: "",
        storeCode: '',
        workingInfo: '',
        processList: [
          {
            "processingattribute": null,
            "procemoney": 0,
            "processcomments": null
          }
        ],
        stockCount: 0,
        currentStockCount: 0,
        goodsType: 0,
        minUtils: 1,
        addUnit: 1, //增加单位
        weightUtils: 1,
        minSaleQty: 1, //最少增加单位
        goodsUnit: '',
        goodsNum: 0,
        weightType: 7,
        isStockCount: true,
        lastStockCountNum: 0,
        barCode: ''
      }
    },
    props: {
      isCheck: {
        type: Boolean,
        default: true
      },
      templateType: {
        type: String,
        defautl: ''
      },
      addCartButtonType: {
        type: Number,
        default: 6
      },
      goodsId: {
        default: 0
      },
      commodityInfor: {
        type: Object,
        default: () => {
          return {}
        }
      },
      pageName: {
        type: String,
        default: ''
      }
    },
    components: {ButtonChangeCart, DetailProce},
    methods: {
      //更改加工类型后更新购物车 数据
      changeProcess(data) {
        this.workingInfo = data
        if (this.goodsNum == 0 && this.number > 0) {
          // console.log('添加')
          this.addCart()
        } else if (this.goodsNum > 0 && this.number > 0) {
          // console.log('上传')
          if (this.goodsNum < this.number) {
            this.$store.dispatch('cjy/addCartAnimate')
          }
          this.updataCart()

        } else if (this.goodsNum > 0 && this.number <= 0) {
          this.deleFromCart()
        }
      },

      changeWorkInfro(data) {
        this.workingInfo = data
      },

      subFromCart() {

        //在购物车内如果想要减少到0 需要提示是否删除
        if ((this.number < this.minUtils || this.number == this.minUtils) && (this.pageName == 'cart' || (this.pageName == 'cartforoffline') && this.goodsType != 8)) {
          MessageBox.confirm('删除商品', {title: "删除商品", message: "是否从购物车中移除该商品", cancelButtonText: '再看看'}).then(
            (res) => {
              this.deleFromCart()
            }
          )
          return
        } else if (this.number == this.minUtils) {
          this.number -= this.minUtils
          //如果是详情页返回
          if (this.pageName == 'detail') {
            return
          }
          this.deleFromCart()
        } else {

          if (this.number <= 0) {
            return
          }
          this.number -= this.addUnit


          //如果是详情页返回
          if (this.pageName == 'detail') {
            return
          }
          this.updataCart()
        }
      },

      async addToCart(isChangeNum = true) {
        if (this.commodityInfor.lastStockCountNum > 0) {
        if (this.storeConfigStatus == 'loaded') {
        } else if (this.storeConfigStatus == 'loading') {
          return
        } else {
          await getConfig()
          if (this.storeConfigStatus != 'loaded') {
            return
          }
        }

        var islocal = (/^localhost:8082+/gi).test(location.host) || this.goodsTrolleyType
        var isXiangpu = navigator.userAgent.indexOf("xiangpu") > -1;         //判断是否在象谱内打开
        if (!isXiangpu && !islocal) {
          this.toDownload()
          return
        }
        var sessionId = localStorage.getItem('sessionId')
        sessionId = sessionId == 'undefined' ? '' : sessionId
        var isLoadShowCart = this.isLoadShowCart
        var weightUtils = this.weightUtils
        var minSaleQty = this.minSaleQty
        var number = this.number
        // 未登录加入购物车
        if (isLoadShowCart && !sessionId) {
          MessageBox.confirm('用户未登录', {title: "用户未登录", message: "请先登录后，再加入购物车", cancelButtonText: '再看看'})
            .then(
              (res) => {
                this.$router.push({path: 'login'})
              }
            )
          return
        }
        // 价格异常不可加入购物测
        if (this.commodityInfor.goodsPrice <= 0) {
          Toast({
            message: '价格异常',
            type: 'fail'
          })
          return
        }

        //  未选择店铺
        if (!this.storeCode) {
          Toast({
            message: '先选择店铺',
            type: 'fail'
          })
          return
        }
        //库存不足不能添加购物车
        if (this.lastStockCountNum < this.number + 1 && this.goodsType != 8) {
          if (this.stockThresholdDeal == 0) {
            Toast({
              message: '库存不足',
              type: 'fail'
            })
          } else {
            Toast({
              message: this.stockThresholdDeal,
              type: 'fail'

            })
          }
          return
        }
        // 超出购物测上限 不能加入购物车
        if (this.number == 0 && this.cartNum >= this.cartMaxNum) {
          Toast({
            message: '超出购物车上限',
            type: 'fail'
          })
          return
        }
        this.number = this.number == 0 ? this.minUtils : this.number + this.addUnit
        if (this.pageName == 'detail' && isChangeNum) {
          return
        }

        // 添加或修改的购物车信息
        if (this.number <= this.minUtils) {
          this.addCart(sessionId)
        } else {
          this.updataCart()
          if (this.goodsType != this.weightType) {
            this.$store.dispatch('cjy/addCartAnimate')
          }
        }

        }
      },

      //将商品加入购物车
      addCart() {
        var sessionId = localStorage.getItem('sessionId')
        sessionId = sessionId == 'undefined' ? '' : sessionId
        if (sessionId) {
          this.ajaxAddCart()
          this.$store.dispatch('cjy/addCartAnimate')
        } else {
          this.$store.commit('cjy/UPDATA_CART_FROM_LOCAL', this.getConfig(true))
          this.$store.dispatch('cjy/addCartAnimate')
        }
      },
      // 上传更新购物车信息
      updataCart() {
        var sessionId = localStorage.getItem('sessionId')
        sessionId = sessionId == 'undefined' ? '' : sessionId
        var isLoadShowCart = this.isLoadShowCart
        // 修改本地购物车数据
        if (!sessionId && !isLoadShowCart) {

          this.$store.commit('cjy/UPDATA_CART_FROM_LOCAL', this.getConfig())
        } else {
          // 已登录修改线上数据源
          this.ajaxupdataCart()
        }

      },

      //从列表中删除
      deleFromCart() {
        var isLoadShowCart = this.isLoadShowCart
        var sessionId = localStorage.getItem('sessionId')
        sessionId = sessionId == 'undefined' ? '' : sessionId

        if (!sessionId && !isLoadShowCart) {
          this.$store.commit('cjy/DELE_CART_FROM_LOCAL', this.addConfig)
          return
        }
        this.ajaxDeleFromCart()
      },

      ajaxAddCart() {
        this.$store.dispatch('cjy/addShoppingCart', this.addConfig)

      },
      ajaxupdataCart() {
        this.$store.dispatch('cjy/updataCart', this.upDateConfig)
      },
      ajaxDeleFromCart() {
        var config = {
          shoppingCartList: [
            {rid: this.rid}
          ]
        }
        this.$store.dispatch('cjy/deleCart', config)
      },


      //初始化参数
      getListFromCart() {
        var data = this.cartList
        var goodsId = this.commodityInfor.goodsId
        var detail = data.find((item) => {
          return item.goodsId == goodsId
        })
        if (!detail) {
          this.number = 0
          this.goodsNum = 0
          return
        }
        this.workingInfo = detail.workingInfo || detail.serve
        this.rid = detail.rid
        this.number = detail.goodsNum
        this.goodsNum = detail.goodsNum || 0
      },

      //更改选中状态
      preOrderUpdata() {
        var upDateConfig = this.upDateConfig
        upDateConfig.goodsId = this.goodsId
        var data = {
          data: [upDateConfig]
        }
        this.$store.commit('cjy/UPDATA_CART', data)
        this.updataCart()
      },

      changeStockCount() {
        this.$emit('changeStockCount', this.number)
      },

      //本地加入购物车
      getConfig(isFisrt = false) {
        var workingInfo = this.workingInfo
        var storeCode = this.storeCode
        var data = this.commodityInfor
        var goodsNum = this.number
        var config = [{
          goodsId: data.goodsId,
          goodsCode: data.goodsCode,
          goodsType: data.goodsType,
          storeCode: this.storeCode || data.storeCode,
          goodsNum: goodsNum,
          serve: '',
          preorder: isFisrt || this.isCheck,
          workingInfo,
          goodsDeliveryType: data.goodsDeliveryType,
          addPrice: data.goodsPrice
        }]
        return config
      },

      //初始化数据
      initData() {
        var minSaleQty = this.commodityInfor.minSaleQty
        var weightUtils = this.commodityInfor.weightUtils
        this.storeCode = localStorage.getItem('storeCode') || ""
        this.processList = this.commodityInfor.processList
        this.stockCount = this.commodityInfor.stockCount
        this.barCode = this.commodityInfor.barCode
        this.currentStockCount = this.commodityInfor.stockCount
        this.goodsDeliveryType = this.commodityInfor.goodsDeliveryType
        this.goodsType = this.commodityInfor.goodsType
        this.weightType = this.commodityInfor.weightType
        this.$emit('changeStockCount', this.number)
        this.goodsUnit = this.commodityInfor.goodsUnit
        this.lastStockCountNum = this.commodityInfor.lastStockCountNum
        this.weightUtils = weightUtils
        this.minSaleQty = minSaleQty
        this.isStockCount = this.lastStockCountNum > 0
      },
    },

    computed: {
      ...mapGetters('cjy', {cartList: 'cartList', cartNum: 'cartNum',}),
      ...mapGetters(['cartConfig', 'storeConfigStatus']),
      isLoadShowCart() {
        return this.$store.state.cjy.isLoadShowCart
      },
      //组合上传到购物车的信息
      addConfig() {
        var workingInfo = this.workingInfo
        var storeCode = this.storeCode
        var goodsUnit = this.goodsUnit
        var data = this.commodityInfor
        var goodsNum = this.number
        var config = [{
          goodsId: data.goodsId,
          goodsCode: data.goodsCode,
          goodsType: data.goodsType,
          storeCode: this.storeCode || data.storeCode,
          goodsNum: goodsNum,
          goodsUnit,
          serve: '',
          workingInfo,
          goodsDeliveryType: data.goodsDeliveryType,
          addPrice: data.goodsPrice
        }]
        return config
      },
      // 更新所用的
      upDateConfig() {
        var workingInfo = this.workingInfo
        var data = this.commodityInfor
        var goodsNum = this.number
        var config = [{
          rid: this.rid,
          goodsNum: goodsNum,
          serve: '',
          workingInfo: workingInfo,
          goodsDeliveryType: data.goodsDeliveryType,
          preorder: this.isCheck
        }]
        return config
      },
      // 库存阙值
      stockThreshold() {
        var getConfigParams = this.cartConfig || {}
        return getConfigParams.stockThreshold || 0
      },
      //最大购物车数量
      cartMaxNum() {
        var getConfigParams = this.cartConfig || {}
        return getConfigParams.cartMaxNum || 999
      },
      //购物车已满提示类型
      stockThresholdDeal() {
        var getConfigParams = this.cartConfig || {}
        return getConfigParams.stockThresholdDeal || 0
      },
      // 浏览器是否可以加入购物车
      goodsTrolleyType() {
        var getConfigParams = this.cartConfig || {}
        return getConfigParams.goodsTrolleyType || 0
      },
      //展示加入购物车的数量
      showNum() {
        var number = this.number
        var showNumber = number
        var minSaleQty = this.minSaleQty
        if (this.commodityInfor.goodsType == 7) {
          showNumber = number == 0 ? 0 : minSaleQty + (number - 1) * this.weightUtils
          showNumber = showNumber * 1000
        }
        return parseInt(showNumber)
      },
      //是否查出剩余库存数量
      isStockCountOver() {
        return this.number >= this.lastStockCountNum
      },
      toDownload() {
        location.href = location.href.split('H5')[0] + 'download/index.html';
      },
    },
    watch: {
      cartList() {
        this.getListFromCart()
      },
      number() {
        this.$emit('choseNum', this.number)
      },
      commodityInfor() {
        this.initData()
      },
    },
    created() {
      
    },
    mounted() {
      this.getListFromCart()
      this.initData()
      if (this.pageName == 'detail' && this.number == 0) {
        this.number = 1
      }
    }
  }
</script>

<style>

</style>
